<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\Sensor;
use common\models\Alert;
use common\models\BehEX;
use common\models\AllEX;
use common\models\FileAlert;
use common\models\FileEX;
use common\models\IPAlert;
use common\models\IPEX;
use common\models\URLAlert;
use common\models\URLEX;
use common\models\Command;
use common\models\SocketConnection;
use common\models\Config;
use yii\helpers\ArrayHelper;
use common\models\Group;

/**
 * Site controller
 */
class AlertController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        if (Config::getLicense()['sensorNowCount'] == 0) {
            $rules = [];
        } else {
            $rules = [
                [
                    'actions' => [''],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['index', 'detail', 'file', 'ip', 'url', 'beh', 'loophole', 'extortion', 'filepage', 'ippage', 'urlpage', 'newpage', 'oldpage', 'by3page', 'chart-data'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'actions' => [],
                    'allow' => true,
                    'roles' => ['admin'],
                ],
            ];
        }
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'detail', 'file', 'ip', 'url', 'beh', 'loophole', 'extortion', 'filepage', 'ippage', 'urlpage', 'newpage', 'oldpage', 'by3page', 'update', 'kill', 'chart-data'],
                'rules' => $rules,
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                // 'logout' => ['post'],
                // 'test' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public $enableCsrfValidation = false;

    public function eventSort($a, $b) {
        if ($a['Timestamp'] == $b['Timestamp']) {
            return 0;
        }
        return ($a['Timestamp'] < $b['Timestamp']) ? -1 : 1;
    }

    private function isAPI() {
        $headers = Yii::$app->request->headers;
        if (stristr($headers['accept'], 'application/json') !== false) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        } else {
            Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        }
    }

    public function actionIndex() {
        $GroupList = Group::find()->orderBy('level')->asArray()->all();
        return $this->render('index', ['GroupList' => $GroupList]);
    }

    public function actionDetail() {
        return $this->render('detail');
    }

    public function actionFile($id) {
        $fileEX = AllEX::find()->where(['rid' => $id, 'Type' => 'File'])->one();
        if (empty($fileEX)) {
            return $this->render('file', [
                        'EX' => ['Label' => '不存在此文件'],
                        'alertData' => [],
                        'sensorOldList' => [],
                        'sensorNowList' => [],
                        'downloadData' => []
            ]);
        }
        $fileAlert = FileAlert::findOne($id);
        if ($fileAlert->status == 0) {
            $fileAlert->status = 1;
            $fileAlert->save();
        }
        $fileEX = ArrayHelper::toArray($fileEX);
        $fileEX['FilePath'] = $fileEX['Label'];
        $pathArr = explode("\\", $fileEX['Label']);
        $fileEX['FileName'] = $pathArr[count($pathArr) - 1];
        $alertData = Alert::find()->where(['AlertID' => $fileEX['AlertID']])->one();
        $alertData = ArrayHelper::toArray($alertData);
//        p($alertData);die;
        $sensorOldList = [];
        $sensorNowList = [];
        $OldList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['MD5' => $fileEX['MD5']])->andWhere(['>', 'status', 1])->asArray()->all();
        $sensorIDOldList = array_column($OldList, 'SensorID');
        $sensorOldList = Sensor::find()->where(['SensorID' => $sensorIDOldList])->all();
        $timeList = array_column($OldList, 'created_at');
        $NowList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['MD5' => $fileEX['MD5']])->andWhere(['<', 'status', 2])->asArray()->all();
        $sensorIDNowList = array_column($NowList, 'SensorID');
        $sensorNowList = Sensor::find()->where(['SensorID' => $sensorIDNowList])->all();
        $timeList = array_merge($timeList, array_column($NowList, 'created_at'));
        sort($timeList);
        $fileEX['maxTime'] = $timeList[count($timeList) - 1];
        $fileEX['miniTime'] = $timeList[0];
        $sensor = Sensor::find()->where(['SensorID' => $alertData['SensorID']])->one();
        $group = $sensor->getGroups()->orderBy(['id' => SORT_DESC])->one();
        if (isset($group)) {
            $groupOne = ArrayHelper::toArray($group);
        } else {
            $groupOne['text'] = '';
        }
        $downloadData = $this->getDownloadData($alertData['EventList']);
        return $this->render('file', [
                    //告警详情
                    'EX' => $fileEX,
                    //event_list
                    'alertData' => $alertData,
                    'sensorOldList' => $sensorOldList,
                    'sensorNowList' => $sensorNowList,
                    'groupOne' => $groupOne,
                    'downloadData' => $downloadData
        ]);
    }

    public function actionIp($id) {
        $ipEX = AllEX::find()->where(['rid' => $id, 'Type' => 'IP'])->one();
        if (empty($ipEX)) {
            return $this->render('ip', ['EX' => ['IP' => '不存在此IP'], 'alertData' => [], 'sensorOldList' => [], 'sensorNowList' => [], 'downloadData' => []]);
        }
        $ipAlert = IpAlert::findOne($id);
        if ($ipAlert->status == 0) {
            $ipAlert->status = 1;
            $ipAlert->save();
        }
        $ipEX = ArrayHelper::toArray($ipEX);
        $alertData = Alert::find()->where(['AlertID' => $ipEX['AlertID']])->one();
        $alertData = ArrayHelper::toArray($alertData);
        $sensorOldList = [];
        $sensorNowList = [];
        $OldList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['IP' => $ipEX['IP']])->andWhere(['>', 'status', 1])->asArray()->all();
        $sensorIDOldList = array_column($OldList, 'SensorID');
        $sensorOldList = Sensor::find()->where(['SensorID' => $sensorIDOldList])->all();
        $timeList = array_column($OldList, 'created_at');
        $NowList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['IP' => $ipEX['IP']])->andWhere(['<', 'status', 2])->asArray()->all();
        $sensorIDNowList = array_column($NowList, 'SensorID');
        $sensorNowList = Sensor::find()->where(['SensorID' => $sensorIDNowList])->all();
        $timeList = array_merge($timeList, array_column($NowList, 'created_at'));
        sort($timeList);
        $ipEX['maxTime'] = $timeList[count($timeList) - 1];
        $ipEX['miniTime'] = $timeList[0];
        $sensor = Sensor::find()->where(['SensorID' => $alertData['SensorID']])->one();
        $group = $sensor->getGroups()->orderBy(['id' => SORT_DESC])->one();
        if (isset($group)) {
            $groupOne = ArrayHelper::toArray($group);
        } else {
            $groupOne['text'] = '';
        }
        $downloadData = $this->getDownloadData($alertData['EventList']);
        return $this->render('ip', [
                    'EX' => $ipEX,
                    'alertData' => $alertData,
                    'sensorOldList' => $sensorOldList,
                    'sensorNowList' => $sensorNowList,
                    'groupOne' => $groupOne,
                    'downloadData' => $downloadData
        ]);
    }

    public function actionUrl($id) {
        $urlEX = AllEX::find()->where(['rid' => $id, 'Type' => 'URL'])->one();
        if (empty($urlEX)) {
            return $this->render('url', [
                        'EX' => ['URL' => '不存在此URL'],
                        'alertData' => [],
                        'sensorOldList' => [],
                        'sensorNowList' => [],
                        'downloadData' => []
            ]);
        }
        $urlAlert = UrlAlert::findOne($id);
        if ($urlAlert->status == 0) {
            $urlAlert->status = 1;
            $urlAlert->save();
        }
        $urlEX = ArrayHelper::toArray($urlEX);
        $alertData = Alert::find()->where(['AlertID' => $urlEX['AlertID']])->one();
        $alertData = ArrayHelper::toArray($alertData);
        $sensorOldList = [];
        $sensorNowList = [];
        $OldList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['URL' => $urlEX['URL']])->andWhere(['>', 'status', 1])->asArray()->all();
        $sensorIDOldList = array_column($OldList, 'SensorID');
        $sensorOldList = Sensor::find()->where(['SensorID' => $sensorIDOldList])->all();
        $timeList = array_column($OldList, 'created_at');
        $NowList = AllEX::find()->select(['SensorID', 'created_at'])->distinct()->where(['URL' => $urlEX['URL']])->andWhere(['<', 'status', 2])->asArray()->all();
        $sensorIDNowList = array_column($NowList, 'SensorID');
        $sensorNowList = Sensor::find()->where(['SensorID' => $sensorIDNowList])->all();
        $timeList = array_merge($timeList, array_column($NowList, 'created_at'));
        sort($timeList);
        $urlEX['maxTime'] = $timeList[count($timeList) - 1];
        $urlEX['miniTime'] = $timeList[0];
        $sensor = Sensor::find()->where(['SensorID' => $alertData['SensorID']])->one();
        $group = $sensor->getGroups()->orderBy(['id' => SORT_DESC])->one();
        if (isset($group)) {
            $groupOne = ArrayHelper::toArray($group);
        } else {
            $groupOne['text'] = '';
        }
        $downloadData = $this->getDownloadData($alertData['EventList']);
        return $this->render('url', [
                    'EX' => $urlEX,
                    'alertData' => $alertData,
                    'sensorOldList' => $sensorOldList,
                    'sensorNowList' => $sensorNowList,
                    'groupOne' => $groupOne,
                    'downloadData' => $downloadData
        ]);
    }

    public function actionBeh($id) {
        $behEX = AllEX::find()->where(['rid' => $id, 'Type' => 'Beh'])->one();
        if (empty($behEX)) {
            return $this->render('beh', ['EX' => [], 'alertData' => []]);
        }
        $alert = Alert::findOne($id);
        if ($alert->status == 0) {
            $alert->status = 1;
            $alert->save();
        }
        $behEX = ArrayHelper::toArray($behEX);
        $alertData = ArrayHelper::toArray($alert);
        usort($alertData['EventList'], array($this, "eventSort"));
        $sensor = Sensor::find()->where(['SensorID' => $alertData['SensorID']])->one();
        $group = $sensor->getGroups()->orderBy(['id' => SORT_DESC])->one();
        if (isset($group)) {
            $groupOne = ArrayHelper::toArray($group);
        } else {
            $groupOne['text'] = '';
        }
        $downloadData = $this->getDownloadData($alert->EventList);
        return $this->render('beh', ['EX' => $behEX, 'alertData' => $alertData, 'groupOne' => $groupOne, 'downloadData' => $downloadData]);
    }

    public function actionLoophole($id) {
        $behEX = AllEX::find()->where(['rid' => $id, 'Type' => 'Beh'])->one();
        if (empty($behEX)) {
            return $this->render('loophole', ['EX' => [], 'alertData' => []]);
        }
        $alert = Alert::findOne($id);
        if ($alert->status == 0) {
            $alert->status = 1;
            $alert->save();
        }
        $behEX = ArrayHelper::toArray($behEX);
        $alertData = ArrayHelper::toArray($alert);
        return $this->render('loophole', ['EX' => $behEX, 'alertData' => $alertData]);
    }

    public function actionExtortion($id) {
        $behEX = AllEX::find()->where(['rid' => $id, 'Type' => 'Beh'])->one();
        if (empty($behEX)) {
            return $this->render('loophole', ['EX' => [], 'alertData' => []]);
        }
        $alert = Alert::findOne($id);
        if ($alert->status == 0) {
            $alert->status = 1;
            $alert->save();
        }
        $behEX = ArrayHelper::toArray($behEX);
        $alertData = ArrayHelper::toArray($alert);
        return $this->render('extortion', ['EX' => $behEX, 'alertData' => $alertData]);
    }

    private function getAlertSensor() {
        $sql = 'SELECT COUNT(DISTINCT SensorID) AS SensorCount FROM AllEX WHERE AllEX.status < 2
                    UNION ALL
                    SELECT COUNT(SensorID) AS SensorCount FROM sensor WHERE sensor.status <> 0';
        return Yii::$app->db->createCommand($sql)->query();
    }

    private function getAlertSrcType() {
        $sql = 'SELECT SrcType,COUNT(rid) AS AlertCount FROM AllEX WHERE AllEX.status < 2 GROUP BY SrcType';
        return Yii::$app->db->createCommand($sql)->query();
    }

    public function actionFilepage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $query = FileEX::find()->where(['IsOld' => 0])->orderBy(['id' => SORT_DESC]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success'
        ];
        return $data;
    }

    public function actionIppage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $query = IPEX::find()->where(['IsOld' => 0])->orderBy(['id' => SORT_DESC]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success'
        ];
        return $data;
    }

    public function actionUrlpage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $query = URLEX::find()->where(['IsOld' => 0])->orderBy(['id' => SORT_DESC]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success'
        ];
        return $data;
    }

    //当前告警的列表
    public function actionNewpage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        //验证筛选条件
        foreach (['stime', 'etime', 'ComputerName', 'AlertType', 'Label', 'MinPoint', 'MaxPoint'] as $value) {
            if (!in_array($value, array_keys($post))) {
                return ['status' => 'fail', 'errorMessage' => '参数错误'];
            }
        }
        $query = AllEX::find()->andWhere(['<', 'status', 2])->orderBy(['created_at' => SORT_DESC, 'id' => SORT_DESC]);
        //当筛选条件有值的时候则加入到搜索语句
        if ($post['stime']) {
            $query = $query->andWhere(['>=', 'created_at', $post['stime']]);
        }
        if ($post['etime']) {
            $query = $query->andWhere(['<=', 'created_at', $post['etime']]);
        }
        if ($post['ComputerName'] && !preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $post['ComputerName'])) {
            $query = $query->andWhere(['=', 'ComputerName', $post['ComputerName']]);
        }
        if ($post['ComputerName'] && preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $post['ComputerName'])) {
            $query = $query->andWhere(['=', 'SensorIP', $post['ComputerName']]);
        }
        if ($post['AlertType'] == 4) {
            $query = $query->andWhere(['IN', 'AlertType', [0, 4, 5]]);
        } else if ($post['AlertType'] == 10) {
            
        } else if ($post['AlertType']) {
            $query = $query->andWhere(['=', 'AlertType', $post['AlertType']]);
        }
        if ($post['Label']) {
            $query = $query->andWhere(['LIKE', 'Label', $post['Label']]);
        }
        if ($post['MinPoint'] >= 0) {
            $query = $query->andWhere(['>=', 'Point', $post['MinPoint']]);
        }
        if ($post['MaxPoint'] >= 0) {
            $query = $query->andWhere(['<=', 'Point', $post['MaxPoint']]);
        }
//        if ($post['gid']) {
//            $sid = GroupSensor::find()->select('group_sensor.sid')->where(['=', 'gid', $post['gid']])->asArray()->all();
//            if ($sid) {
//                $sensor_id = Sensor::find()->select('SensorID')->where(['IN', 'id', array_column($sid, 'sid')])->asArray()->all();
//                $query = $query->andWhere(['IN', 'SensorID', array_column($sensor_id, 'SensorID')]);
//            } else {
//                $query = $query->andWhere('1=2');
//            }
//        }
        if ($post['gid']) {
            $group = Group::findOne($post['gid']);
            if (isset($group)) {
                $SensorIDList = $group->getSensorIDList();
            } else {
                $SensorIDList = [];
            }
            $query = $query->andWhere(['IN', 'SensorID', $SensorIDList]);
        }
        //提供按照sensorID查找告警
        if (array_key_exists('SensorID', $post) && $post['SensorID']) {
            $query = $query->andWhere(['=', 'SensorID', $post['SensorID']]);
        }
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success'
        ];
        return $data;
    }

    public function actionOldpage($page = 1, $rows = 15, $IsSolveBy3rd = 0) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
            $IsSolveBy3rd = empty($post['IsSolveBy3rd']) ? $IsSolveBy3rd : $post['IsSolveBy3rd'];
        }
        $query = AllEX::find()->where(['IsSolveBy3rd' => $IsSolveBy3rd])->andWhere(['>', 'status', 1])->orderBy(['created_at' => SORT_DESC, 'id' => SORT_DESC]);
        //提供按照sensorID查找告警
        if (array_key_exists('SensorID', $post) && $post['SensorID']) {
            $query = $query->andWhere(['=', 'SensorID', $post['SensorID']]);
        }
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success'
        ];
        return $data;
    }

    public function actionBy3page($page = 1, $rows = 15, $IsSolveBy3rd = 0) {
        return $this->actionOldpage($page, $rows, 1);
    }

    public function actionUpdate() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['List'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'List error';
            return $data;
        }
        $page = empty($post['page']) ? 1 : (int) $post['page'];
        $type = empty($post['type']) ? 'setOld' : $post['type'];
        $command_types = [
            'setOld' => Command::MSG_M2E_RESLOVE_OBJECT, //解决告警
            'setWhite' => Command::MSG_M2E_UPDATE_WHITELIST_1, //加入白名单
            'setOldBeh' => Command::MSG_M2E_RESLOVE_ALERT, //解决告警
            'setWhiteBeh' => Command::MSG_M2E_IGNORE_ALERT, //加入例外
            'delWhite' => Command::MSG_M2E_REMOVE_WHITELIST, //移除白名单
            'delWhiteBeh' => false //取消例外
        ];
        foreach ($post['List'] as $key => $item) {
            $command = new Command();
            $command->SensorID = $item['SensorID'];
            $command->Type = $command_types[$type];
            $json = ['AlertID' => $item['AlertID']];
            if (isset($item['MD5'])) {
                $json['MD5'] = $item['MD5'];
                $json['SHA256'] = $item['SHA256'];
                FileAlert::change($type, $item);
            } elseif (isset($item['IP'])) {
                $json['IP'] = $item['IP'];
                IPAlert::change($type, $item);
            } elseif (isset($item['URL'])) {
                $json['URL'] = $item['URL'];
                URLAlert::change($type, $item);
            } elseif ($type == 'setOldBeh' || $type == 'setWhiteBeh') {
                Alert::change($type, $item);
            } elseif ($type == 'delWhiteBeh') {
                Alert::change($type, $item);
                continue;
            }
            $command->data = $json;
            $command->send();
            $command->save();
            if (($key + 1) < count($post['List'])) {
                usleep(20000);
            }
        }
        if ($type == 'delWhiteBeh' || $type == 'delWhite') {
            $data = $this->actionOldpage($page);
        } else {
            return $data;
//            $data = $this->actionNewpage($page);
        }
        return $data;
    }

    public function actionKill() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        $command = new Command();
        $command->SensorID = $post['SensorID'];
        $command->Type = Command::MSG_M2S_KILL_PROCESS;
        $json = [
            'Path' => $post['ProcessName'],
            'PID' => $post['PID'],
            'SensorID' => $post['SensorID'],
        ];
        $command->data = $json;
        $command->send();
        $command->save();
        if ($command->status == Command::STATUS_UNSENT) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Connection failed';
        }
        return $data;
    }

    public function actionChartData() {
        $this->isAPI();
        $data = [
            'chartData' => [
                'AlertSensor' => $this->getAlertSensor(),
                'AlertSrcType' => $this->getAlertSrcType(),
            ],
            'status' => 'success',
        ];
        return $data;
    }

    public function getDownloadData($EventList) {
        $TypeName = [
            'NONE' => '未知',
            'NETWORK_CONNECT' => '网络连接',
            'DNS_QUERY' => 'DNS查询',
            'CREATE_FILE' => '新建文件',
            'DELETE_FILE' => '删除文件',
            'RENAME_FILE' => '重命名文件',
            'WRITE_FILE' => '写入文件',
            'SET_FILETIME_TO_PAST' => '修改文件时间到过去',
            'HIDE_FILE' => '隐藏文件',
            'COPY_FILE' => '复制文件',
            'CREATE_PE_FILE' => '新建可执行文件',
            'WRITE_PE_FILE' => '写入可执行文件',
            'READ_PE_FILE' => '读取可执行文件',
            'DELETE_PE_FILE' => '删除可执行文件',
            'RENAME_PE_FILE' => '重命名可执行文件',
            'REG_CREATE_KEY' => '新建注册表',
            'REG_DELETE_KEY' => '删除注册表',
            'REG_DELETE_VALUE' => '删除注册表内容',
            'REG_SET_VALUE' => '设置注册表内容',
            'REG_RENAME_KEY' => '重命名注册表',
            'CREATE_PROCESS' => '创建进程',
            'EXIT_PROCESS' => '退出进程',
            'INJECT_PROCESS' => '注入进程',
            'CMD_COMMAND' => 'CMD命令',
            'CREATE_USER_ACCOUNT' => '新建用户账户',
            'DELETE_USER_ACCOUNT' => '删除用户账户',
            'ADD_USER_ACCOUNT_TO_GROUP' => '新建用户账户到组',
            'NET_SHARE_ADD' => '创建网络共享',
            'NET_SHARE_DEL' => '删除网络共享',
            'WINDOWS_SERVICE_CREATE' => '创建服务',
            'WINDOWS_SERVICE_START' => '启动服务',
            'WINDOWS_SERVICE_STOP' => '停止服务',
            'USB_PLUG_ARRIVAL' => '插入USB',
            'USB_PLUG_REMOVAL' => '拔出USB',
            'USER_LOGON' => '用户登录',
            'IMAGE_LOAD_TO_SENSITIVE' => '重要进程/DLL',
            'CLEAR_EVENT_LOG' => '清除事件日志',
            "REG_SAVE_SAM" => 'REG_SAVE_SAM',
            "LSASS_MIMIKATZ" => 'LSASS_MIMIKATZ',
            "HTTP_REQUEST" => 'HTTP_REQUEST'
        ];
        $downloadData = [];
        foreach ($EventList as $event) {
            $data = [
                'EventID' => $event['EventID'],
                'time' => date('Y-m-d H:i:s', $event['Timestamp'] / 1000),
                'event' => $event['SrcObj']['name'] . '  -->  ' . $event['TarObj']['LongName'],
                'type' => array_key_exists($event['EventAction'], $TypeName) ? $TypeName[$event['EventAction']] : $event['EventAction'],
                'ComputerName' => $event['ComputerName'],
            ];
            $downloadData[] = $data;
        }
        return $downloadData;
    }

    public function actionDownloadCsv($id) {
        $alert = Alert::find()->where(['AlertID' => $id])->one();
        if (isset($alert)) {
            $downloadData = $this->getDownloadData($alert->EventList);
        } else {
            $downloadData = [];
        }
        $EXCEL_OUT = iconv('UTF-8', 'GBK', "事件ID,时间,事件,事件类型,计算机\n");
        foreach ($downloadData as $key => $item) {
            $EXCEL_OUT .= iconv('UTF-8', 'GBK', $item['EventID'] . ',' .
                    $item['time'] . ',' .
                    $item['event'] . ',' .
                    $item['type'] . ',' .
                    $item['ComputerName'] .
                    "\n"
            );
        }
        $headers = Yii::$app->response->headers;
        $headers->set('Cache-Control', 'max-age=0');
        $headers->set('Content-Disposition', "attachment;filename=" . $id . ".csv");
        return $EXCEL_OUT;
    }

    public function actionDownloadJson($id) {
        $alert = Alert::find()->where(['AlertID' => $id])->one();
        if (isset($alert)) {
            $downloadData = $this->getDownloadData($alert->EventList);
        } else {
            $downloadData = [];
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $headers = Yii::$app->response->headers;
        $headers->set('Cache-Control', 'max-age=0');
        $headers->set('Content-Disposition', "attachment;filename=" . $id . ".json");
        return $downloadData;
    }

}
